package org.example.lock;

import org.junit.jupiter.api.Test;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
 *Author:ZouHeng
 *Des:测试公平锁和非公平锁
 *Date:2021-01-05  16:37
 */
public class FairAndUnfairTest {
    private static Lock fairLock = new ReentrantLock(true);
    private static Lock unfairLock = new ReentrantLock(false);

    @Test
    public void fair() {
        System.out.println("测试公平锁");
        testLock(fairLock);
    }

    @Test
    public void unfair() {
        System.out.println("测试非公平锁");
        testLock(unfairLock);
    }

    private void testLock(Lock lock) {
        for (int i = 0; i < 5; i++) {
            Thread job = new Job(lock);
            job.setName("Thread-" + i);
            job.start();
        }
    }

    private static class Job extends Thread {
        private Lock lock;
        public Job(Lock lock) {
            this.lock = lock;
        }
        public void run() {
            // 连续2次打印当前的Thread和等待队列中的Thread（略）
            lock.lock();
            System.out.println("当前Thread：" + Thread.currentThread().getName());
            System.out.println("当前Thread：" + Thread.currentThread().getName());
            lock.unlock();
        }
    }

    private static class ReentrantLock2 extends ReentrantLock {
        public ReentrantLock2(boolean fair) {
            super(fair);
        }
        public Collection<Thread> getQueuedThreads() {
            List<Thread> arrayList = new ArrayList<>(super.
                    getQueuedThreads());
            Collections.reverse(arrayList);
            return arrayList;
        }
    }
}
